/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taskmanager2ndedition.server;

import taskmanager2ndedition.User;
import taskmanager2ndedition.exceptions.SessionNotFoundException;
import taskmanager2ndedition.exceptions.UserNotFoundException;
import taskmanager2ndedition.exceptions.WrongPasswordException;

/**
 *
 * @author denaas
 */
public class SecurityManager {
    private SessionManager sessionManager;
    private UserManager userManager;
    
    public SecurityManager(SessionManager sessionManager, UserManager userManager){
        this.sessionManager = sessionManager;
        this.userManager = userManager;
    }

    public User impersonate(int sessionId, int userId) throws SessionNotFoundException, 
            UserNotFoundException{
        Session theSession = sessionManager.findSession(sessionId);
        
        if (checkPrivileges(theSession.getUser())){
            return userManager.findById(userId);
        }
        return theSession.getUser();
    }
    
    public User getSelf(int sessionId) throws SessionNotFoundException, 
            UserNotFoundException{
        Session theSession = sessionManager.findSession(sessionId);
        return theSession.getUser();
    }

    public Session authorize(String login, String password) throws UserNotFoundException, WrongPasswordException{
        User theUser = userManager.findByLogin(login);
        if (checkPassword(password, theUser.getPassword())){
            return sessionManager.startSession(theUser);
        }
        return  null;  
    }

    public boolean checkPrivileges(User user){
        return user.isAdmin();
    }

    public boolean checkPassword(String password, long truePassword) throws WrongPasswordException{
        if (password.hashCode() != truePassword)
           throw new WrongPasswordException();
        return true;
    }
}
